import random
import time

import cv2
import numpy as np

from api.InternalConfig import *
from minidevice import MiniDevice


class Command:
    # 设备handle
    device_: MiniDevice = None

    def __init__(self, device):
        self.device_ = device

    def click(self, x: int, y: int, duration: int = 100):
        """
        点击
        :param x: x坐标
        :param y: y坐标
        :param duration: 持续时间
        """
        self.device_.click(x, y, duration=100)

    def grab(self):
        """
        捕捉当前的帧
        """
        # 当前的状态图
        rawBytes = self.device_.screenshot_raw()
        # 二进制数据流转 np.ndarray [np.uint8: 8位像素]
        convertedBytes = np.frombuffer(rawBytes, np.uint8)
        # 显示图
        img = cv2.imdecode(convertedBytes, cv2.IMREAD_COLOR)
        return img

    def save(self, imgName: str):
        """
        保存当前帧
        :param imgName: 图的名字,内部调用cv2.imwrite,不同的文件名后缀保存为不同的格式
        """
        img = self.grab
        cv2.imwrite(imgName, img)

    def propsOpen(self):
        """
        打开道具栏
        """
        # 获得范围内的坐标
        x = random.randint(propsWidthBounds[0], propsWidthBounds[1])
        y = random.randint(propsHeightBounds[0], propsHeightBounds[1])
        # 打开
        self.device_.click(x, y)

    def propsClose(self):
        """
        关闭道具栏
        """
        # 获得范围内的坐标
        x = random.randint(propsCloseWidthBounds[0], propsCloseWidthBounds[1])
        y = random.randint(propsCloseHeightBounds[0], propsCloseHeightBounds[1])
        # 打开
        self.device_.click(x, y)

    def give(self, coordinate):
        # 点击给予
        # 获得范围内的坐标
        x = random.randint(giveWidthBounds[0], giveWidthBounds[1])
        y = random.randint(giveHeightBounds[0], giveHeightBounds[1])
        # 打开
        self.device_.click(x, y)
        # 等待
        time.sleep(random.uniform(0.2, 0.5))
        # 点击目标坐标
        self.device_.click(coordinate[0], coordinate[1])
        # 选择目标

    def hideOther(self):
        self.device_.swipe([(1307, 479), (1553, 251)], 0)
        self.device_.swipe([(1193, 454), (989, 663)], 0)
        pass
